/**
 * Created by wangkui on 2016/1/26.
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var authTypes = ['facebook', 'twitter', 'google', 'sina', 'qq','wechat'];

var UserSchema = new Schema({
    nickname: String,
    email: { type: String, lowercase: true },
    mobile: { type: String },
    avatarId:{type: String},
    role: {type: String, default: 'user'},
    hashedPassword: String,
    salt: String,
    source:String,
    provider: String,
    wechat: {},
    weibo: {},
    qq: {},
    facebook: {},
    twitter: {},
    regdate: { type: Date, default: Date.now }

},{collection: 'users'});


UserSchema
    .virtual('password')
    .set(function(password) {
        this._password = password;
        this.salt = this.makeSalt();
        this.hashedPassword = this.encryptPassword(password);
    })
    .get(function() {
        return this._password;
    });


UserSchema.methods = {
    /**
     * Authenticate - check if the passwords are the same
     *
     * @param {String} plainText
     * @return {Boolean}
     * @api public
     */
    authenticate: function(plainText) {
        return this.encryptPassword(plainText) === this.hashedPassword;
    },

    /**
     * Make salt
     *
     * @return {String}
     * @api public
     */
    makeSalt: function() {
        return crypto.randomBytes(16).toString('base64');
    },

    /**
     * Encrypt password
     *
     * @param {String} password
     * @return {String}
     * @api public
     */
    encryptPassword: function(password) {
        if (!password || !this.salt) return '';
        var salt = new Buffer(this.salt, 'base64');
        return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64');
    }
};

module.exports = mongoose.model('User', UserSchema);